package com.medishare.fragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.medishare.R;
import com.medishare.activity.ActivityCallCenter;
import com.medishare.activity.ActivityQuizResult;
import com.medishare.activity.ActivityTestQuestions;
import com.medishare.activity.MainActivity;
import com.medishare.adapter.AdapterCallAssistant;
import com.medishare.adapter.AdapterDisease;
import com.medishare.data.DataMember;
import com.medishare.data.DataQuiz;
import com.medishare.util.OnitemClickListener;
import com.medishare.util.Utils;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FragmentTestQuestion extends Fragment{

	private Activity mainActivity;
	private GridView mGridView;
    public final static String  TAG = FragmentTestQuestion.class.getSimpleName();
    public final static boolean DEBUG = true;
    private String selectedId = "";
	private TextView mTVPhysique;
	private TextView mTVContent;
	private TextView mTVTestNumber;
	private TextView mTVTotalNumber;
	private String answerid;
	private OnitemClickListener listener;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		selectedId = getArguments().getString("selectedId");
		answerid = getArguments().getString("answerid");
		View view = inflater.inflate(R.layout.fragment_health_quiz, null);
		
		mGridView = (GridView) view.findViewById(R.id.grid_answer);
		mTVPhysique = (TextView) view.findViewById(R.id.tv_physique);
		mTVContent = (TextView) view.findViewById(R.id.tv_quiz_content);
		mTVTestNumber = (TextView) view.findViewById(R.id.tv_tested_number);
		mTVTotalNumber = (TextView) view.findViewById(R.id.tv_total_number);
		String url = "";
		if(!answerid.equals(""))
			url = Utils.getBaseUrl() + "Test/quiz/?uuid=" + Utils.getDeviceUUID(mainActivity) + "&member_id="+selectedId + "&answer=" + answerid;
		else
			url = Utils.getBaseUrl() + "Test/quiz/?uuid=" + Utils.getDeviceUUID(mainActivity) + "&member_id="+selectedId;
		if(DEBUG){
			Log.i(TAG,url);
		}
		loadData(url);
		return view;
	}
	
	private void loadData(String url) {
		 AsyncHttpClient client = new AsyncHttpClient();
			final ArrayList<String> answers = new ArrayList<String>(); 
			final DataQuiz quiz = new DataQuiz();
			client.get(url, new AsyncHttpResponseHandler(){

				@Override
				public void onSuccess(String content)  {
					super.onSuccess(content);
					Message msg = new Message();
					try {
						
						JSONObject jsonObject = new JSONObject(content);
						int status = jsonObject.getInt("status");
						if(status == 0){
							msg.what = 1;
							mHandler.sendMessage(msg);
							return;
						}
						if(status == 2){
							msg.what = 2;
							msg.obj = content;
							mHandler.sendMessage(msg);
							return;
						}
						JSONObject jsonData = jsonObject.getJSONObject("data");
						quiz.setTestNumber(jsonData.getInt("testNumber"));
						quiz.setTestAll(jsonData.getString("testAll"));
						JSONObject jsonResult = jsonData.getJSONObject("result");
						String content1 = jsonResult.getString("content");
						String physique = jsonData.getString("physique");
						quiz.setContent(content1);
						quiz.setPhysique(physique);
						JSONArray jsonArray = jsonData.getJSONArray("answer");
						for(int i=0;i<jsonArray.length();i++){
							String temp = jsonArray.getString(i);
							answers.add(temp);
						}
						quiz.setAnswers(answers);
						
					} catch (JSONException e) {
						e.printStackTrace();
					}
					msg.what = 0;
					msg.obj = quiz;
					mHandler.sendMessage(msg);
				}
				
			});		
	}


	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mainActivity =  activity;
		//listener = (OnitemClickListener) activity;
		
	}
	
  
    
	Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what){
			case 0:
				DataQuiz datas = (DataQuiz) msg.obj;
				mTVContent.setText(datas.getContent());
				mTVPhysique.setText(datas.getPhysique());
				mTVTestNumber.setText(String.format(mainActivity.getResources().getString(R.string.health_test_tested_number),datas.getTestNumber()+""));
				mTVTotalNumber.setText(String.format(mainActivity.getResources().getString(R.string.health_test_total_number),datas.getTestAll()+""));
				
				final AdapterDisease adapter = new AdapterDisease(mainActivity, datas.getAnswers());
				mGridView.setAdapter(adapter);
				mGridView.setOnItemClickListener(new OnItemClickListener() {

					private View currentSelectedView;

					@Override
					public void onItemClick(AdapterView<?> parent, View v,
							int position, long id) {
						if (currentSelectedView != null && currentSelectedView != v) {
					        unhighlightCurrentRow(currentSelectedView);
					    }
                        
						currentSelectedView = v;
					    highlightCurrentRow(currentSelectedView);
					    
					    listener.onItemClick(position);
					   
					}
				});
				break;
			case 1:
				break;
			case 2:
				String content = (String) msg.obj;
				Intent i = new Intent(mainActivity,ActivityQuizResult.class);
			    i.putExtra("content", content);
			    mainActivity.startActivity(i);
			    mainActivity.finish();
				break;
			}
		}
    	
    };
	
    private void unhighlightCurrentRow(View rowView) {
    	rowView.setBackgroundResource(R.drawable.bg_default_textview);
    	((TextView)rowView).setTextColor(Color.BLACK);
    }

    private void highlightCurrentRow(View rowView) {
        rowView.setBackgroundResource(R.drawable.bg_selected_textview);
        ((TextView)rowView).setTextColor(Color.WHITE);
    }

	
    
    
}
